<?php 
if (!defined('BASEPATH')){
	exit('No direct script access allowed');
}

/**
 * Adminlog Controller
 * Build by Phuc Nguyen
 * Contact : nguyenvanphuc0626@gmail.com
 */

class BookingStatus extends BACKEND_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->language('bookingStatus');
		$this->load->language('button');
		if($this->database_connect_status){
			$this->load->model('bookingStatus_model');
                        $this->load->model('user_model');
			$this->set_controller('bookingStatus');
			$this->set_model($this->bookingStatus_model);
		}
                $this->load->library('bookinglib');
                $this->bookinglib = new bookinglib();
	}
        
        private function menuTop(){
            $this->load->model('stats_model');
            $user_info                          = $this->stats_model->get_user_info($this->stats_model->get_user_id());
            $this->view_data['role_by_group']   = $user_info['role_list'];
            $this->view_data['username']        = $user_info['username'];
            return $this->view_data;
        }
        
        public function paymentConfirm(){
                $this->menuTop();
                
                $this->view_data['customerID']                  =  $this->input->get('customerID');
                $this->load->view('auth/bookingStatus/payment_confirm', $this->view_data);
        }

        public function detailCustomers(){
            $this->bookinglib->direct();
            $info                                           = $this->bookingStatus_model->find_by(array('id'=>$this->input->get('id')));

                $this->view_data['role_by_group'] 		= array();
		if($this->database_connect_status){
			$this->load->model('stats_model');
			$user_info = $this->stats_model->get_user_info($this->stats_model->get_user_id());
			$this->view_data['role_by_group'] = $user_info['role_list'];
			$this->view_data['username'] 	  = $user_info['username'];
                        $this->view_data['info']          = $info[0];

                        $this->load->view('auth/bookingStatus/view', $this->view_data);
                } else {
                        $this->view_data['flash_message']	= $this->lang->line('database_connect_failed');
                        $this->load->view('templates/backend/error', $this->view_data);	
                }            
        }

        protected function update($params=NULL){
		if($this->input->server('REQUEST_METHOD')=='POST'){
                        $this->view_data["booking"]                                 = new stdClass();
                        $this->view_data["booking"]->booking_types                  = $this->input->post('booking_types');
                        $this->view_data["booking"]->booking_customer_name          = preg_replace("/[\n\r]/","|",strtoupper(trim($this->input->post('customersName'))));
                        $this->view_data["booking"]->booking_child                  = trim($this->input->post('child'));
                        $this->view_data["booking"]->total_pax                      = $this->input->post('total_pax');
                        $this->view_data["booking"]->net_fare                       = $this->input->post('net_fare_fake');
                        $this->view_data["booking"]->sale_fare                      = $this->input->post('sale_fare_fake');
                        $this->view_data["booking"]->note                           = $this->input->post('note');
                        $this->view_data["booking"]->advance                        = 0;
                        $this->view_data["booking"]->owner                          = $this->session->userdata['user_id'];
                        $this->view_data["booking"]->lastupdated                    = time();
                        
                        $booking_id                                                 = $this->input->post('booking_id');
                        $booking_info_u                                             = $this->input->post('booking-info');
                        $this->view_data["booking"]->booking                        = json_encode($booking_info_u);
                        if(isset($params) && $params){
                            $this->bookingStatus_model->update($this->view_data["booking"], $params);
                            $logAction                     = $this->lang->line('update_booking_success').$params;
                        }
                        
                        //update voucher if price change;
                        if($this->input->post('voucher_id')){
                            $this->load->model('voucher_model');
                            $this->view_data["voucher"]                         = new stdClass();
                            
                            $result     = $this->voucher_model->find_by(array('id'=>$this->input->post('voucher_id')));
                            
                            $pnr        = json_decode($result[0]->booking_place_code);
                            $j_net      = json_decode($result[0]->net);
                            $j_sale     = json_decode($result[0]->sale);
                            
                            $m_net      =   array();$sum_net        =   0;
                            $m_sale     =   array();$sum_sale       =   0;
                            
                            foreach($pnr as $keys => $vals){
                                if(trim($vals) == $this->input->post('booking_place_code')){
                                    $m_net[$keys]        =   $this->view_data["booking"]->net_fare;
                                    $m_sale[$keys]       =   $this->view_data["booking"]->sale_fare;
                                } else {
                                    $m_net[$keys]        =   $j_net[$keys];
                                    $m_sale[$keys]       =   $j_sale[$keys];
                                }
                                
                                $sum_net        +=   $m_net[$keys];
                                $sum_sale       +=   $m_sale[$keys];
                            }

                            $this->view_data['voucher']->net            = json_encode($m_net);
                            $this->view_data['voucher']->sale           = json_encode($m_sale);
                            $this->view_data['voucher']->net_fare       = $sum_net;
                            $this->view_data['voucher']->sale_fare      = $sum_sale;
                            
                            $this->voucher_model->update($this->view_data["voucher"], $this->input->post('voucher_id'));
                            unset($this->view_data['voucher']);
                        }// end voucher_id
                        
                        //end control log
                        unset($this->view_data["booking"]);
                        if($params){
                                $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                                $paramAdminLog  = array(
                                    'userid'            => $this->session->userdata['user_id'],
                                    'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                    'ip'                => $_SERVER['REMOTE_ADDR'],
                                    'logAction'         => $logAction,
                                    'agent_code'        => $this->session->userdata['agent_code']
                                );
                                $this->user_model->insertUserAdminLog($paramAdminLog);

                                redirect('auth/bookingStatus');
                        }
            }
            
            $this->load->model('bookingStatus_model');
            $this->load->model('language_model');

            if(isset($params)){
                    $bookingStatus_query	= $this->bookingStatus_model->find_by(array('id' => $params));
                    if(!isset($bookingStatus_query[0])){
                            $this->session->set_flashdata('flash_message', $this->lang->line('not_exists'));
                            redirect(site_url('auth/bookingStatus'));
                            exit();
                    }

                    $this->view_data['bookingStatus']				= $bookingStatus_query[0];
            }else{
                    $this->view_data["bookingStatus"]->id	 		= $params;
            }

            $this->view_data['js'] = array(
                            base_url().'static/templates/backend/js/main.js'
            );
            
            if($this->view_data['bookingStatus']->owner != $this->session->userdata['user_id']){
                    redirect(site_url('auth/bookingStatus'));
            }
            $this->load->view('auth/bookingStatus/edit', $this->view_data);
	}
        
        public function delete(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $this->load->model("voucher_model");
                $bookingStatus_query        = $this->bookingStatus_model->find_by(array('id' => $this->input->post('id')));
                $data_fake                  = array('booking_id'=>$this->input->post('id'));
                
                if($bookingStatus_query[0]->voucher_id){
                        $this->load->model('voucher_model');
                        $this->voucher_model->delete(array('id'=>$bookingStatus_query[0]->voucher_id));
                }
                
                switch ($bookingStatus_query[0]->payment_method){
                    case '2':
                        $this->load->model('ticket_model');
                        $this->ticket_model->delete($data_fake);
                       break;
                    case '3':
                        $this->load->model('bank_model');
                        $this->bank_model->delete($data_fake);
                       break;
                    case '4':
                        $this->load->model('debts_model');
                        $this->debts_model->delete($data_fake);
                       break;
                   case '5':
                       $this->load->model('office_model');
                       $this->office_model->delete($data_fake);
                       break;
                }
                $this->bookingStatus_model->delete(array('id' => $this->input->post('id')));
                $this->session->set_flashdata('flash_message', $this->lang->line('delete_successful'));
                
                if($this->input->post('session') == "air"){
                    //'[DeleteBookingHold]--'
                    $c_session  =   '[DeleteBookingHoldAir]--';
                } else {
                    $c_session  =   '[DeleteBookingHold]--';
                }
                
                $paramAdminLog  = array(
                    'userid'            => $this->session->userdata['user_id'],
                    'lastLogin'         => date('Y-m-d :H:i:s',time()),
                    'ip'                => $_SERVER['REMOTE_ADDR'],
                    'logAction'         => $c_session.$bookingStatus_query[0]->airline.'--'.$bookingStatus_query[0]->booking_place_code.'--'.$this->input->post('deletebk'),
                    'agent_code'        => $this->session->userdata['agent_code']
                );

                $this->user_model->insertUserAdminLog($paramAdminLog);
                die("0");
            }
            
            $bookingStatus_query        = $this->bookingStatus_model->find_by(array('id' => $this->input->get('id')));
            if($bookingStatus_query[0]->voucher_id != NULL){
                $this->view_data['voucher_id']                      =   $bookingStatus_query[0]->voucher_id;
                $this->view_data['payment_confirm']                 =   $bookingStatus_query[0]->payment_cofim;
            }
            $this->view_data['id']              =   $this->input->get('id');
            $this->view_data['session']         =   $this->input->get('session');
            $this->load->view('auth/bookingStatus/deletebk', $this->view_data);
        }
        
        public function updateBill(){
            $this->bookinglib->direct();
            $this->menuTop();
            
            if($this->input->server('REQUEST_METHOD')=='POST'){
                
                $this->view_data["bookingStatus"]                                       = new stdClass();
                $this->view_data["bookingStatus"]->dkve                                 = $this->input->post('dkve');
                $this->view_data["bookingStatus"]->dkhanhly                             = $this->input->post('dkhanhly');
                $this->view_data["bookingStatus"]->condition_print                      = ($this->input->post('condition_print') == 'true')?'1':'0';

                $id                                                                     = $this->input->post('id');
                $this->bookingStatus_model->update($this->view_data["bookingStatus"],$id);
                $this->session->set_userdata('hiddenCty', $this->input->post('hiddenCty'));
                if($id){
                        $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                        $paramAdminLog  = array(
                            'userid'            => $this->session->userdata['user_id'],
                            'lastLogin'         => date('Y-m-d :H:i:s',time()),
                            'ip'                => $_SERVER['REMOTE_ADDR'],
                            'logAction'         => $this->lang->line("update_bill_success").$id,
                            'agent_code'        => $this->session->userdata['agent_code']
                        );
                        $this->user_model->insertUserAdminLog($paramAdminLog);
                }
                die($id);
            }
            
            
            $info                                       = $this->bookingStatus_model->find_by(array('id'=>$this->input->get('id')));
            $this->view_data['css']			= array(STATIC_URL.'backend/css/page.css');
            $this->view_data['info']                    = $info[0];
            
            $this->load->view('auth/bookingStatus/updatebill', $this->view_data);
        }
        
        public function printbill(){
            $this->bookinglib->direct();
            $this->load->model('configuration_model');
            $this->load->model('bookhistory_model');
            $info       = $this->bookingStatus_model->find_by(array('id'=>$this->input->get('id')));
            $tmp        = json_decode($info[0]->booking);
            $a          = explode("-",$tmp[0]);
            
            $nguoilon = explode("||", $info[0]->booking_customer_name);
            if($info[0]->booking_child){
                $child = explode(",",$info[0]->booking_child);
                foreach($child as $vals){
                    $nguoilon[] = trim($vals);
                }
            }
            
            if($this->session->userdata('hiddenCty') == "false"){
                $hidden = false;
            } else {
                $hidden = true;
            }
            
            $info       = array(
                'booking_place_code'    =>  $info[0]->booking_place_code,
                'sale_fare'             =>  $info[0]->sale_fare,
                'booking_customer_name' =>  array_chunk($nguoilon, 2),
                'booking'               =>  $tmp,
                'dkve'                  =>  $info[0]->dkve,
                'dkhanhly'              =>  $info[0]->dkhanhly,
                'condition_print'       =>  $info[0]->condition_print,
                'logo'                  =>  substr($a[1],0,2),
                'hiddenCty'             =>  $hidden
            );
            $this->session->unset_userdata('hiddenCty');
            $this->view_data['css']			= array(
				STATIC_URL.'backend/css/page.css',
		);
            
            $this->view_data['info']                          = $info;
            $this->view_data['configuration']                 = $this->configuration_model->find_by();
            unset($tmp);unset($a);
            
            $this->load->view('auth/bookingStatus/printbill', $this->view_data);
        }
        
        public function receipt(){
            $this->bookinglib->direct();
            $this->load->model('configuration_model');
            $this->load->model('bookhistory_model');

            $info       = $this->bookingStatus_model->find_by(array('id'=>$this->input->get('id')));
            
            $this->view_data['css']			= array(
				STATIC_URL.'backend/css/page.css',
		);
            
            $info[0]->real_fare                               = $info[0]->sale_fare;
            $info[0]->booking_id                              = $info[0]->id;
            $this->view_data['info']                          = $info[0];
            $this->view_data['configuration']                 = $this->configuration_model->find_by();
            
            $this->load->view('auth/bookhistory/receipt', $this->view_data);
        }
        
        public function sendsms(){
            $this->load->model('listcustomers_model');
            $this->load->model('bookairport_model');
            
            $booking_info               = $this->bookingStatus_model->find_by(array('id' => $this->input->get('id')));
            $listcustomers_query	= $this->listcustomers_model->find_by(array('customerID' => $booking_info[0]->customerID));
            
            $this->view_data['customer']= $listcustomers_query[0]->name;
            $this->view_data['phone']   = json_decode($listcustomers_query[0]->phone);
            
            //info customers
            $this->view_data['paxname']     = explode("||", $booking_info[0]->booking_customer_name);
            if($booking_info[0]->booking_child){
               $child = explode(',',$booking_info[0]->booking_child);
               foreach($child as $keys => $vals){
                   $this->view_data['paxname'][] = trim($vals);
               }
            }
            $content                        = '';
            $noidung                        = array();
            foreach(json_decode($booking_info[0]->booking) as $key => $vals){
                $info       = explode("-", $vals);
                
                $sbdi       = $this->bookairport_model->find_by(array('code'=>trim($info[3])));
                if(empty($sbdi)){
                        $content               = json_decode(file_get_contents(PRE_API_AIRPORT.trim($info[3]).'?isDestination=false&ccy=VND'));
                        $_info      = array(
                            'code'         =>  trim($content[0]->PlaceId),
                            'city'         =>  trim($content[0]->CityName),
                            'cityEn'       =>  trim(str_replace("City", "", $content[0]->CityNameEn)),
                            'country'      =>  trim($content[0]->CountryName),
                            'countryEn'    =>  trim($content[0]->CountryName)
                        );
                        $this->bookairport_model->create($_info);
                        unset($_info);unset($content);
                }
                $sbdi       = trim($sbdi[0]->cityEn);
                $giodi      = str_replace(':','h',trim($info[2]));
                
                $sbden      = $this->bookairport_model->find_by(array('code'=>trim($info[5])));
                if(empty($sbden)){
                        $content               = json_decode(file_get_contents(PRE_API_AIRPORT.trim($info[5]).'?isDestination=false&ccy=VND'));
                        $_info      = array(
                            'code'         =>  trim($content[0]->PlaceId),
                            'city'         =>  trim($content[0]->CityName),
                            'cityEn'       =>  trim(str_replace("City", "", $content[0]->CityNameEn)),
                            'country'      =>  trim($content[0]->CountryName),
                            'countryEn'    =>  trim($content[0]->CountryName)
                        );
                        $this->bookairport_model->create($_info);
                        
                        unset($_info);unset($content);
                }
                $sbden          = trim($sbden[0]->cityEn);
                
                $times          = explode('/', $info[0]);
                $noidung[]      .=  $sbdi.'-'.$sbden.', ngay '.$times[0].'/'.$times[1].' luc '.$giodi.' '.$info[1];
            }
            
            switch ($booking_info[0]->airline){
                case 'VN':
                    $title = 'VIETNAMAIR';break;
                case 'VJ':
                    $title = 'VIETJET';break;
                case 'BL':
                    $title = 'JESTAR';break;
                default :
                    $title = '';break;
            }
            
            $response     = array(
                'airline'   =>      $title,
                'pnr'       =>      $booking_info[0]->booking_place_code,
                'paxname'   =>      $this->view_data['paxname'],
                'message'   =>      $noidung,
                'total'     =>      $this->bookinglib->my_number_format($booking_info[0]->sale_fare,2, ',', ',').'VNĐ'
            );
            
            if($booking_info[0]->owner != $this->session->userdata['user_id'] && $this->session->userdata['group_id'] != 1){
                $this->view_data['checker']     =   false;
            } else {
                $this->view_data['checker']     =   true;
            }
            
            $this->view_data['noidung'] = json_encode($response);
            $this->load->view('auth/bookhistory/sendsms', $this->view_data);
        }
        
        public function timeLimit(){
                if($this->input->server('REQUEST_METHOD')=='POST'){
                    if($this->input->post('timeLimit')){
                        $this->bookingStatus_model->timeLimit(array('timeLimit'=>date("Y-m-d H:i:s",strtotime($this->input->post('timeLimit'))),'id'=>$this->input->post('id')));
                        die("0");
                    } else {
                        die('1');
                    }
                }
                $info                           = $this->bookingStatus_model->find_by(array('id'=>$this->input->get('id')));
                $this->view_data['info']        =   $info[0];
                $this->load->view('auth/bookingStatus/timeLimit', $this->view_data);
        }
        
        public function voucher(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $this->load->model('voucher_model');
                $json   = json_decode($this->input->post('id'));
                $id     = explode(",",$json);
                $error  = array();
                $count  = false;
                foreach($id as $key => $vals){
                    $check  =   $this->bookingStatus_model->find_by(array('id'=>$vals));
                    $data   =   array(
                        'airline'               =>  $check[0]->airline,
                        'booking_place_code'    =>  $check[0]->booking_place_code,
                        'createdTime'           =>  $check[0]->createdTime
                    );
                    $result =   $this->voucher_model->checkVoucher($data);
                    if($result){
                        $count = true;
                        $error[$key] = array(
                            "error"         =>  1,
                            "msg"           =>  $check[0]->booking_place_code.'-'.$check[0]->airline." đã tồn tại trong CT số ".$result[0]->id
                        );
                    } else {
                         $error[$key] = array(
                            'error' =>  0,
                            'msg'   =>  ''
                        );
                    }
                }
                if($count){
                    die(json_encode($error));
                } else {
                    $this->view_data    =   new stdClass();
                    $this->load->view('auth/bookingStatus/voucher', $this->view_data);
                }
            } else {
                redirect('/auth');
            }
        }
        
        public function checkCustomer(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $id             = $this->input->post('id');
                
                if(count($id)>1){
                    $demo           = $this->bookingStatus_model->find_by(array('id'=>$id[0]));
                    $i = 2;
                    while($i <= count($id)){
                        $test   =    $this->bookingStatus_model->find_by(array('id'=>$id[$i-1]));
                        if($test[0]->customerID != $demo[0]->customerID){
                            die("1");
                        }
                        $i++;
                    }
                }
                
            } else {
                redirect('/auth');
            }
        }
}

/* End of file bookingStatus.php */
/* Location: ./application/controllers/auth/bookingStatus.php */